package com.yx.services.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yx.entity.Stock;
import com.yx.mapper.StockMapper;
import com.yx.services.IStockService;
import com.yx.vo.StockParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.support.TransactionCallback;
import org.springframework.transaction.support.TransactionTemplate;

import java.util.List;

/**
 * @Classname StockServiceImpl
 * @Date 2021/07/09 19:03
 * @Author by yx
 * @Description TODO:
 */
@Service
public class StockServiceImpl extends ServiceImpl<StockMapper, Stock> implements IStockService {

    /*
    * 注入事务模板,用户自行设置事务--->
    * 事务出现问题需要回滚
    * 使用了全局异常捕获,抛出异常会被全局异常捕获,导致事务回滚后,业务断开不能正常的运行下去.
    * */
    @Autowired
    private TransactionTemplate template;


    @Override
    public Boolean lockGoodsStock(List<StockParam> stockParamList) {
        return template.execute(new TransactionCallback<Boolean>() {
            @Override
            public Boolean doInTransaction(TransactionStatus status) {
                // 1.创建事务保存点,用于事务回滚
                Object savepoint = status.createSavepoint();
                //2.设置标识,判断库存是否扣减成功;默认扣减成功
                Boolean flag = true;
                for (StockParam stockParam : stockParamList) {
                    Integer stock = baseMapper.lockGoodsStock(stockParam);
                    if (stock<=0) {
                        flag = false;
                        // 回滚事务
                        status.rollbackToSavepoint(savepoint);
                        break;
                    }
                }

                return flag;
            }
        });
    }

    @Override
    public Boolean unLockGoodsStock(List<StockParam> stockParamList) {
        return template.execute(new TransactionCallback<Boolean>() {
            @Override
            public Boolean doInTransaction(TransactionStatus status) {
                // 1.创建事务保存点,用于事务回滚
                Object savepoint = status.createSavepoint();
                //2.设置标识,判断库存是否扣减成功;默认扣减成功
                Boolean flag = true;
                for (StockParam stockParam : stockParamList) {
                    Integer stock = baseMapper.unlockGoodsStock(stockParam);
                    if (stock<=0) {
                        flag = false;
                        // 回滚事务
                        status.rollbackToSavepoint(savepoint);
                        break;
                    }
                }

                return flag;
            }
        });
    }
}
